import requests , re, time , json
from io import BytesIO


from django_redis import get_redis_connection


from django.core.paginator import Paginator  #
from django.shortcuts import render,redirect,reverse
from django.http import JsonResponse,HttpResponse
from django.views.generic import View
from apps.spider_account import models
from django.conf import settings
from utils.loginMixin.mixin import LoginRequiredMixin
from django_redis import get_redis_connection
# Create your views here.

from utils.encrypt.encrypt import md5
# 显示抓取号列表页
class ShowSpiderList(LoginRequiredMixin,View):
    def get(self,request):
        wechat_list = models.WechatUserModel.objects.filter(is_delete=0)
        for index in wechat_list:
            index.password = md5(index.password)
        return render(request, 'wx_list.html', {"wechat_list": wechat_list})

# 删除抓取号
class DeleteSpiderAccountView(LoginRequiredMixin,View):
    def post(self, request):
        wechat_code_id = request.POST.get("user_id", None)
        # 从数据库获取wechat
        wechat = models.WechatUserModel.objects.filter(id=wechat_code_id).exists()
        if not wechat:
            return JsonResponse({"status": False, "message": "要删除的数据不存在"})
        else:
            wechat_obj = models.WechatUserModel.objects.filter(id=wechat_code_id).first()
            wechat_obj.is_delete = True
            wechat_obj.save()
            return JsonResponse({"status": True, "message": "删除成功"})


# 新增抓取号
class AddSpiderAccountView(LoginRequiredMixin,View):
    def post(self, request):
        user_name = request.POST.get("username", None)
        pwd = request.POST.get("pwd", None)
        adminer = request.POST.get("adminer", None)
        adminer_wx = request.POST.get("adminer_wx", None)
        if not all([user_name, pwd, adminer, adminer_wx]):
            return JsonResponse({'status': False, "message": "数据信息显示不完整"})
        try:
            user = models.WechatUserModel.objects.get(wechat_code=user_name.strip())
        except:
            user = None
        if user:
            return JsonResponse({'status': False, "message": "{}用户已经存在，请勿新增重复抓取号".format(user_name)})
        user = models.WechatUserModel.objects.create(
            wechat_code=user_name, password=pwd, scaner=adminer, adminer_wechat_id=adminer_wx
        )
        # 这里其实要做一个微信密码校验
        user.save()
        return JsonResponse({'status': True, "message": "{}用户添加成功".format(user_name), 'hrefs': '/spider/account/show/spider/list/'})


# 编辑抓取号
class EditAccountView(LoginRequiredMixin,View):
    def post(self, request):
        # 获取用户id
        user_id = request.POST.get("user_id", None)
        wechat_code = request.POST.get("user_name", None)
        password = request.POST.get("pwd", None)
        scaner = request.POST.get("nickname", None)
        adminer_wechat_id = request.POST.get("wechat_wxcode", None)
        if not all([wechat_code, password, scaner, adminer_wechat_id]):
            return JsonResponse({'status': False, "message": "用户输入信息不完整"})
        if not models.WechatUserModel.objects.filter(id=user_id).exists():
            return JsonResponse({'status': False, "message": "修改的账号不存在"})
        users = models.WechatUserModel.objects.get(id=user_id)
        users.wechat_code = wechat_code
        users.password = password
        users.scaner = scaner
        users.adminer_wechat_id = adminer_wechat_id
        users.save()
        return JsonResponse({'status': True})



# 删除抓取号功能
class DeleteAccountView(LoginRequiredMixin,View):
    def post(self, request):
        wechat_code_id = request.POST.get("user_id", None)
        # 从数据库获取wechat
        wechat = models.WechatUserModel.objects.filter(id=wechat_code_id).exists()
        if not wechat:
            return JsonResponse({"status": False, "message": "要删除的数据不存在"})
        else:
            wechat_obj = models.WechatUserModel.objects.filter(id=wechat_code_id).first()
            wechat_obj.is_delete = True
            wechat_obj.save()
            return JsonResponse({"status": True, "message": "删除成功"})

# 登陆
class SinginView(LoginRequiredMixin,View):
    def get(self, request, user_id):
        user = models.WechatUserModel.objects.filter(id=user_id).first()
        if not user:
            return render(request, 'login_scner.html', {"user": user, 'err_msg': ""})
        else:
            return render(request, 'login_scner.html', {"user": user, 'err_msg': ""})


# 显示二维码
class ShowImage(LoginRequiredMixin,View):
    '''生成带有用户名密码的二维码 '''
    def get(self, request, user_id):
        from utils.Login.wechatLogin import WeChatLogin
        user = models.WechatUserModel.objects.filter(id=user_id).first()
        if not user:
            return JsonResponse({"status": False})
        user_name = user.wechat_code
        pwd = user.password  # 从数据库获取对应的user_id
        UserAgent = request.META.get("HTTP_USER_AGENT")  # 携带用户的请求头
        wechat_obj = WeChatLogin(UserAgent, user_name, pwd)
        cookies = wechat_obj.get_new_token()
        redirect_url = wechat_obj.redirect_url

        if not cookies:
            print("用户名或密码错误")
            return None
        lists = []
        for k, v in cookies.items():
            lists.append(str(k) + "=" + str(v))
        headers = {
            'authority': "mp.weixin.qq.com",
            'method': "GET",
            'path': "/cgi-bin/loginqrcode?action=getqrcode&param=4300&rd=967",
            'scheme': "https",
            'accept': "image/webp,image/apng,image/*,*/*;q=0.8",
            'accept-encoding': "gzip, deflate, br",
            'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
            'referer': "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account={}&token=".format(
                user_name),
            'user-agent': UserAgent,
            "cookie": ";".join(lists),
        }
        img_src = "https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=getqrcode&param=4300&rd=579"
        response = requests.get(img_src, headers=headers)
        # 写入redis数据库
        conn = get_redis_connection()
        conn.set(user_name, ";".join(lists))
        conn.expire(user_name, 60)  # 设置过期时间
        return HttpResponse(BytesIO(response.content))


class CheckLogin(LoginRequiredMixin,View):
    def get(self, request):
        time.sleep(1)
        UserAgent = request.META.get("HTTP_USER_AGENT")
        username = request.GET.get("username", None)
        conn = get_redis_connection()
        cookies = conn.get(username)  # 登陆的用户
        if not cookies:
            return JsonResponse({"status":False,"errmsg":"获取cookies失败"})
        data = self.check_scaner_status(useragent=UserAgent,cookies=cookies,username=username)  # 返回轮询的结果
        if not data:
            return JsonResponse({"status":False,"message":"用户名或密码错误"})
        if data.get("base_resp").get("err_msg") != "ok":
            return JsonResponse({'status': False, "message": "扫码 登陆错误"})
        elif data.get("status", None) == 0:
            return JsonResponse({'status': False, "message": "等待用户扫码", "data": data})
        elif data.get("status", None) == 4:
            return JsonResponse({'status': False, "message": "扫码成功,等待用户确认登陆", "data": data})
        elif data.get("status", None) == 1:
            dict_cookie = {cookie.split('=')[0]: cookie.split('=')[1] for cookie in cookies.decode("utf-8").split(';')}
            print(dict_cookie)
            # 获取cookies 写入redis数据库中 并设置状态 前端列表页短时间内无法再登陆
            # 获取cookie
            login_urls = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=login"
            login_headers = {
                'authority': "mp.weixin.qq.com",
                'method': "POST",
                'path': "/cgi-bin/bizlogin?action=login",
                'scheme': "https",
                'accept': "*/*",
                'accept-encoding': "gzip, deflate, br",
                'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
                "content-length": "60",
                'cookie': cookies.decode("utf-8"),
                "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                'referer': "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account={}&token=".format(
                    username),
                'user-agent': UserAgent,
                'x-requested-with': "XMLHttpRequest",
            }
            formdata = {
                "userlang": "zh_CN",
                "redirect_url": "",
                "token": "",
                "lang": "zh_CN",
                "f": "json",
                "ajax": "1"
            }
            response_start_login = requests.post(url=login_urls, headers=login_headers, data=formdata)

            print("start login cookies", response_start_login.json())
            if not response_start_login.json().get("redirect_url", None):
                pass  # 登陆失败
            redirect_url = response_start_login.json().get("redirect_url", None)
            token = ''.join(re.findall("token=(\d+)", str(redirect_url)))  # 获取用户的tokenid
            for i in response_start_login.cookies.items():
                if len(i) == 2:
                    dict_cookie[i[0]] = i[1]
            # 获取最终的cookie 存放到redis数据库中
            cookie_list = list()
            for k, v in dict_cookie.items():
                cookie_list.append(str(k) + "=" + str(v))
            home_url = "https://mp.weixin.qq.com{}".format(redirect_url)
            home_headers = {
                'authority': "mp.weixin.qq.com",
                'method': "GET",
                'path': str(redirect_url),
                'scheme': "https",
                'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                'accept-encoding': "gzip, deflate, br",
                'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
                'cookie': ';'.join(cookie_list),
                'referer': "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account={}&token=".format(
                    username),
                'user-agent': UserAgent,
                "upgrade-insecure-requests": "1",
                'x-requested-with': "XMLHttpRequest",
            }
            print(';'.join(cookie_list))
            print("主页", home_url)
            home_response = requests.get(url=home_url, headers=home_headers)
            print("最终返回的cookies字典", home_response.cookies.items())
            for i in home_response.cookies.items():
                if len(i) == 2:
                    dict_cookie[i[0]] = i[1]
            print("最终的cookies", dict_cookie)
            last_cookie_str = list()
            for k, v in dict_cookie.items():
                last_cookie_str.append(str(k) + "=" + str(v))
            last_cookie_str = ';'.join(last_cookie_str)
            redis_conn = get_redis_connection()
            redis_headers = dict()
            redis_headers[
               'Referer'] = "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=10&token={token}&lang=zh_CN".format(
               token=token)
            redis_headers['Cookie'] = last_cookie_str
            redis_headers['token'] = token
            redis_headers['redirect_url'] = redirect_url
            redis_headers['user-agent'] = UserAgent
            redis_conn.hset(settings.REDIS_COOKIES_NAME,username,json.dumps(redis_headers))  # 保存到redis中用来抓取
            # return redirect(reverse("spiders_account:spiders_list"))
            model_user = models.WechatUserModel.objects.filter(wechat_code=username).first()
            model_user.token = token
            model_user.cookies = redis_headers
            model_user.save()
            return JsonResponse({'status': True, "message": "用户登陆成功", "data": data,'hrefs':'/spider/account/show/spider/list/'})
        else:
            return JsonResponse({'status': False, "message": "未知错误", "data": data})

    def check_scaner_status(self, useragent, cookies, username):
        """监听用户扫码的结果"""
        start_urls = "https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1"
        headers = {
            'authority': "mp.weixin.qq.com",
            'method': "GET",
            'path': "/cgi-bin/loginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1",
            'scheme': "https",
            'accept': "*/*",
            'accept-encoding': "gzip, deflate, br",
            'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
            'cookie': cookies.decode("utf-8"),
            'referer': "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account={}&token=".format(
                username),
            'user-agent': useragent,
            'x-requested-with': "XMLHttpRequest",
        }
        response = requests.get(url=start_urls, headers=headers)
        if response.status_code ==200:
            data = json.loads(response.text)
            return data
        else:
            return None

    def last_start_login(self,cookies,username,UserAgent):
        login_urls = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=login"
        login_headers = {
            'authority': "mp.weixin.qq.com",
            'method': "POST",
            'path': "/cgi-bin/bizlogin?action=login",
            'scheme': "https",
            'accept': "*/*",
            'accept-encoding': "gzip, deflate, br",
            'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
            "content-length": "60",
            'cookie': cookies.decode("utf-8"),
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            'referer': "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account={}&token=".format(
                username),
            'user-agent': UserAgent,
            'x-requested-with': "XMLHttpRequest",
        }
        formdata = {
            "userlang": "zh_CN",
            "redirect_url": "",
            "token": "",
            "lang": "zh_CN",
            "f": "json",
            "ajax": "1"
        }
        response_start_login = requests.post(url=login_urls, headers=login_headers, data=formdata)
        if response_start_login.status_code == 200:
            return response_start_login
        else:
            return None
